﻿using System.IO;
using System.Runtime.Serialization;

namespace Rodunu.Business.Logic
{
    public class Serializer<T>
    {
        public void SerializeToFile(T items, string filename)
        {
            var contractSerializer = new DataContractSerializer(typeof(T));
            using (Stream s = File.Create(filename))
                contractSerializer.WriteObject(s, items);  
        }

        private static T DeserializeFromFile(string filename)
        {
            var contractSerializer = new DataContractSerializer(typeof(T));
            if (!File.Exists(filename))
            {
                File.Create(filename);
            }
            using (Stream s = File.OpenRead(filename))
                return (T)contractSerializer.ReadObject(s); 
        }

        public T Deserialize(string FileName)
        {
            return DeserializeFromFile(FileName);
        }

        public string SerializeToString(T items)
        {
            var contractSerializer = new DataContractSerializer(typeof(T));

            string objString;
            using (var s = new MemoryStream())
            {
                contractSerializer.WriteObject(s, items);
                byte[] bytes = s.ToArray();
                objString = System.Text.Encoding.UTF8.GetString(bytes);
            }

            return objString;
        }

        public T DeserializeFromString(string items)
        {
            var contractSerializer = new DataContractSerializer(typeof(T));

            byte[] b = System.Text.Encoding.UTF8.GetBytes(items);
            using (MemoryStream ms = new MemoryStream(b))
            {
                return (T)contractSerializer.ReadObject(ms);
            }
        }
    }
}